package com.site_assembly.common;


import com.site_assembly.exception.TicketArgsException;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.Set;

public class ValidationUtils {

    private static final ValidatorFactory FACTORY = Validation.buildDefaultValidatorFactory();


    /**
     * 验证成功不返回任何消息，认证失败则抛出TicketArgsException
     * @param object
     * @param groups
     */
    public static void validate(Object object, Class<?>... groups) {
        Validator validator = FACTORY.getValidator();

        Set<ConstraintViolation<Object>> constraintViolations = validator.validate(object, groups);

        if (!constraintViolations.isEmpty()) {

            StringBuilder messageBuilder = new StringBuilder();
            for (ConstraintViolation<Object> violation : constraintViolations) {
                messageBuilder.append(violation.getPropertyPath());
                messageBuilder.append(":");
                messageBuilder.append(violation.getMessage());
                messageBuilder.append("!\n");
            }
            String message = messageBuilder.toString().substring(0,messageBuilder.toString().length()-1);
            throw new TicketArgsException(message) ;
        }

    }

}
